<template>
  <view class="inner-wrapper">
    <MescrollUni ref="mescrollRef" :down="downOption" :up="upOption" @init="mescrollInit" @down="downCallback">
      <view class="background-top">
        <view class="block-wrapper npb">
          <view class="top-top" @click="goInfoProgress">
            <view class="top-t">
              <view class="top-m">
                <view class="title18" @click="onClickLogin">{{
                  site.employeeName
                    ? site.employeeName
                    : user.name
                      ? user.name
                      : weixinInfo.nickName
                        ? weixinInfo.nickName
                        : "--"
                }}</view>
                <text class="yilizhi" v-if="userStatus === 1">待入职</text>
                <text class="yilizhi" v-else-if="userStatus === 4">已离职</text>
                <img v-if="userStatus===4" class="top-renzhen2" src="/static/images/renzheng.png">
                <img v-else class="top-renzhen2" :src="
                    verified == true
                      ? '/static/images/renzheng.png'
                      : '/static/images/weirenzheng.png'
                  ">
                <view class="top-renz" :class="{colB9B: userStatus === 4}">{{  verified == true ? "已认证" : "未认证" }}</view>
              </view>
              <view class="title14">{{ site.companyName || "游客" }}</view>
            </view>
            <image class="userinfo-avatar" :src="myInfo.avatar" />
          </view>
        </view>
      </view>

      <view class="block-wrapper npb">
        <view class="notice-wrapper" @click="goNotice">
          <span class="flex">
            <i class="iconfont  primary_color iconfont font18">&#xe6bd;</i>
          </span>
          <div class="notice-tip">
            <view v-if="companyId" class="swiper">
              <view class="swiper-item uni-bg-red">欢迎使用{{ settings.name }}小程序</view>
            </view>
            <swiper v-else class="swiper" vertical="true" :circular="circular" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval" :duration="duration">
              <swiper-item v-for="(item, index) in noticelist" :key="index">
                <view class="swiper-item uni-bg-red">{{ item.title }}</view>
              </swiper-item>
            </swiper>
          </div>
          <i class="arrow iconfont  primary_color iconfont font18">&#xe6bc;</i>
        </view>
      </view>
      <view v-if="!site.companyName" class="intoJob" @click="openIntoJob">
        <view class="intoJob1">
          <view class="intoJob1Box">
            <view class="">
              立即入职
            </view>
            <view class="intoJob1Boxyzm">
              输入动态验证码
            </view>
          </view>
          <view>
            <img class="images22" src="../entryAll/static/22.png" alt="">
          </view>
        </view>
       <view style="display: flex;">
        <view class="bgc-light flex-center-center" style="width: 20px; height: 20px; border-radius: 50%">
          <u-icon name="arrow-right" class="tc-theme fs12" />
        </view>
      </view>
      </view>
      <view class="block-wrapper npb">
        <view class="work-wrapper">
          <span class="work-top">{{workName}}</span>
          <view class="work-flow-box">
            <template v-for="(item, index) in workbench">
              <view v-if="!(isJF && ['工资条', '考勤打卡', '社保公积金'].includes(item.name))" :key="index" class="flow-box-inner flex-column" @tap="onWorkbench(item)">
                <view v-if="item.icon[1]" class="moduleBox">
                  <image style="width:100%;height:100%;margin-bottom:0 " :src="item.icon[1]" />
                  <view style="position:absolute;left:26rpx">
                    <view style="font-size: 34rpx;font-weight: 400;color:#222426">{{item.name}}</view>
                    <view style="font-size: 24rpx;font-weight: 400;color:#9C9C9C;margin-top:8rpx">{{item.desc?item.desc:'---'}}</view>
                  </view>
                  <view style="position:absolute;right:10rpx;top:12rpx">
                    <image style="width:112rpx;height:112rpx" :src="item.icon[0]" />
                  </view>
                </view>
                <view v-else class="moduleBox">
                  <view :style="{ width: '100%', height: '100%', 'margin-bottom': 0, 'background-color': item.bgColor ? item.bgColor : 'transparent', position: 'relative', 'border-radius': '20rpx', 'overflow': 'hidden'}">
                    <view style="position: absolute; left: 26rpx; top: 13px">
                      <view style="font-size: 34rpx;font-weight: 400;color:#222426">{{item.name}}</view>
                      <view style="font-size: 24rpx;font-weight: 400;color:#9C9C9C;margin-top:8rpx">{{item.desc?item.desc:'---'}}</view>
                    </view>
                    <view style="position:absolute;right:10rpx;top:12rpx">
                      <image style="width:112rpx;height:112rpx" :src="item.icon[0]" />
                    </view>
                  </view>
                </view>
              </view>
            </template>
          </view>
        </view>
      </view>

      <view class="block-wrapper npb" v-if="publicList && publicList.length > 0">
        <view class="work-wrapper">
          <span class="work-top">{{publicName}}</span>
          <view class="work-flow-box">
            <view v-for="(item, index) in publicList" :key="index" class="flow-box-inner-csxr flex-column" @tap="onGongYi(item)">
              <image class="flow-image" :src="item.icon" mode="widthFix" />
            </view>
          </view>
        </view>
      </view>
      <view v-if="settings.id === 'csxr'" class="block-wrapper" style="margin-bottom: 50px">
        <view class="img-wrapper" @tap="goRC">
          <image src="http://hjrl-public.oss-cn-qingdao.aliyuncs.com/excel/footer.png" mode="widthFix" class="flow-image" />
        </view>
      </view>
      <view v-else-if="settings.id === 'zxr'" class="block-wrapper">
        <image src="/static/images/bg.png" class="flow-image2" />
        <span class="work-top2">行业信息</span>
        <view v-for="(item, index) in hangyeinfo" :key="index" class="top-top-hangye" @click="hangyeClick(item)">
          <view class="hangye-m">
            <view class="hangye-title">{{ item.articleTitle }}</view>
          </view>
          <view class="hangye-img">
            <image class="hangye-img2" :src="item.mainPictureUrl" />
          </view>
        </view>
      </view>
      <view style="height:85px" />
    </MescrollUni>
    <u-modal :show-confirm-button='false' @cancel="cancel" :mask-close-able="true" v-model="showModal" title='动态验证码' :title-style="{color: settings.theme}">
      <view class="showModalTitle marBottom24">请输入动态验证码</view>
      <view class="marBottom24">
        <u-message-input :activeColor="settings.theme" inactive-color='#2F2F2F' :value='codeInput' @finish="finish" mode="box"></u-message-input>
      </view>
      <view style=" margin: 0 auto;text-align: center;">
        <view class="qrrz" @click="getByDynamicCode">确认入职</view>
      </view>
    </u-modal>
    <u-top-tips ref="uTips" />
  </view>
</template>
<script>
import { theme_primary } from "@/uni.scss";
import { verify_home, verify_token } from "@/utils/public";
import { mapState, mapGetters } from "vuex";
import MescrollUni from "@/components/mescroll-uni/mescroll-uni.vue";
import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";
import {
  listSysNoticeByUser,
  getMyInfoReq,
  getArtcal,
  getSwitch,
  getSwitchModule,
  getByDynamicCode,
} from "@/services/contract";
export default {
  name: "HomeTab",
  components: { MescrollUni },
  mixins: [MescrollMixin],
  props: {},
  data() {
    return {
      codeInput: "",
      showModal: false,
      publicList: [],
      publicName: "",
      workName: "",
      weixinInfo: {},
      userStatus: uni.getStorageSync("userStatus"),
      workbench: [],
      csxrList: [
        {
          url: "/static/images/index/zhengce.png",
          path: "/publicWelfare/fagui",
        }, // 政策法规
        {
          url: "/static/images/index/gongyigang.png",
          path: "/publicWelfare/gongyigang",
        }, // 公益动态岗
        {
          url: "/static/images/index/tuijian.png",
          path: "/publicWelfare/tuijian",
        }, // 推荐岗位
      ],
      mescroll: null,
      upOption: {
        use: false,
        auto: false, // 默认开始不执行上拉
      },
      downOption: {
        use: false,
        auto: false, // 默认开始不执行上拉
        textInOffset: "下拉更新个人信息", // 下拉的距离在offset范围内的提示文本
        textLoading: "更新中 ...", // 加载中的提示文本
        textOutOffset: "释放更新个人信息", // 下拉的距离大于offset范围的提示文本
        textErr: "更新失败",
        textSuccess: "更新成功",
        bgColor: theme_primary,
        beforeEndDelay: 1000,
      },
      myInfo: {
        companyName: "",
        name: "",
        verified: false,
        percentage: "0",
        avatar: "/static/images/moren.png",
      },
      isSwitch: false,
      hangyeinfo: [],
      noticelist: [],
      indicatorDots: false,
      autoplay: true,
      circular: true,
      interval: 2500,
      duration: 500,
      isMounted: false,
      lock: false,
    };
  },
  computed: {
    ...mapGetters(['isJF']),
    ...mapState(["site", "settings", "user"]),
    ...mapState({
      item: (state) => state.register.item,
      ticket: (state) => state.register.ticket,
    }),
    companyId() {
      return this.site ? this.site.companyId : null;
    },
    userId() {
      return this.user.userId;
    },
    verified() {
      return this.site.verified;
    }
  },
  watch: {
    companyId: {
      handler(newVal) {
        if (uni.getStorageSync("token")) {
          this.downOption.use = true;
        }
        if (newVal) {
          this.getMyInfo();
          this.getSwitch();
          this.getSysNoticeList(this.site.companyId);
          if (this.userId) {
            this.getSwitchModule(this.site.companyId);
          }
        }
        if (this.settings.id === "zxr") {
          // 获取行业信息
          const data = {
            pageNo: 1,
            pageSize: 3,
          };
          getArtcal(data).then((res) => {
            this.hangyeinfo = res.entities;
          });
        }
      },
      immediate: true,
    },
    userId(newVal) {
      if (!newVal) {
        this.workbench = [];
      }
    },
  },
  created() {
    uni.getUserInfo({
      provider: "weixin",
      success: (res) => {
        res.userInfo.nickName =
          res.userInfo.nickName === "微信用户"
            ? "点击登录"
            : res.userInfo.nickName;
        this.weixinInfo = res.userInfo;
      },
      fail: (err) => {
        console.log("debug log --> ", err);
      },
    });
  },
  mounted() {
    this.isMounted = true;
  },
  methods: {
    init() {
      this.lock = false;
    },
    finish(e) {
      console.log("输入结束，当前值为：" + e);
      this.codeInput = e;
    },
    getByDynamicCode() {
      const data = {
        code: this.codeInput,
      };
      getByDynamicCode(data).then((res) => {
        uni.showToast({
          title: "操作成功",
          icon: "none",
          duration: 1500,
        });
        const siteObject = JSON.stringify(res);
        this.showModal = false;
        this.codeInput = "";
        uni.navigateTo({
          url: `/entryAll/manualAdd/manualAdd?code=${this.codeInput}&siteObject=${siteObject}`,
        });
      });
    },
    openIntoJob() {
      this.showModal = true;
      this.codeInput = "";
    },
    onClickLogin() {
      const name = this.site.employeeName
        ? this.site.employeeName
        : this.user.name
        ? this.user.name
        : this.weixinInfo.nickName
        ? this.weixinInfo.nickName
        : "--";
      console.log("eee", name);
      if (name === "点击登录") {
        uni.navigateTo({
          url: "/authorize/index",
        });
      }
    },
    //递归处理数据icon字段为数组
    editIcon(data) {
      data.forEach((item, index) => {
        item.icon = item.icon.split(",");
        if (item.childList && item.childList.length) {
          this.editIcon(item.childList);
        }
      });
    },
    //查询应用已开启的模块
    getSwitchModule(companyId) {
      getSwitchModule({
        isHide: 1,
        subjectId: companyId,
        subjectType: "company",
        code: this.settings.code,
      }).then((res) => {
        res.forEach((item, index) => {
          if (item.code === "gongyigang") {
            this.publicList = item.childList;
            this.publicName = item.name;
          }
          if (item.code === "gongzuotai") {
            this.workbench =
              this.userStatus === 4
                ? item.childList.filter(
                    (z) =>
                      z.name === "工资条" ||
                      z.name === "电子合同" ||
                      z.name === "社保公积金" ||
                      z.name === "消息通知"
                  )
                : item.childList;
            this.workName = item.name;
            this.editIcon(this.workbench);
          }
        });
      });
    },
    mescrollInit(mescroll) {
      this.mescroll = mescroll;
    },
    /* 下拉刷新的回调*/
    downCallback() {
      // 与 mescroll-body 的处理方式一致 >
      if (this.isMounted) {
        verify_home()
          .then(() => {
            this.mescroll.endSuccess(); // 跟新成功
          })
          .catch(() => {
            this.mescroll.endErr();
          });
        if (this.userId) {
          this.getSwitchModule(this.site.companyId);
        }
      }
    },
    hangyeClick(item) {
      // 跳转到内部窗口并且传递链接
      uni.setStorageSync("content", item.content);
      uni.navigateTo({
        url: `/webView/index`,
      });
    },
    goRC() {
      uni.navigateToMiniProgram({
        appId: "wx60b1a78d00ebd732",
        success(res) {
          // 打开成功
        },
        fail(res) {
          uni.showToast({
            title: "华杰人才网打开失败",
            icon: "none",
            duration: 2000,
          });
        },
      });
    },
    onWorkbench(data) {
      if (this.lock) return false;
      this.lock = true;
      verify_token()
        .then(() => {
          setTimeout(() => {
            this.lock = false;
          }, 3000);
          uni.navigateTo({
            url: data.link,
          });
        })
        .catch(() => {
          setTimeout(() => {
            this.lock = false;
          }, 3000);
          uni.navigateTo({
            url: "/authorize/index",
          });
        });
    },
    onGongYi(data) {
      const itemss = encodeURIComponent(JSON.stringify(data.childList));
      uni.navigateTo({
        url: data.link + "?item=" + itemss,
      });
    },
    goRegisterIndex() {
      if (this.checkIdentity()) {
        return false;
      }
      uni.redirectTo({
        url: "/register/form?item=" + this.item,
      });
    },
    goRegisterForm() {
      if (this.checkIdentity()) {
        return false;
      }
      uni.redirectTo({
        url: "/register/form?ticket=" + this.ticket,
      });
    },
    goReport() {
      if (this.checkIdentity()) {
        return false;
      }
      uni.navigateTo({
        url: "/report/index",
      });
    },
    goMessage() {
      if (this.checkIdentity()) {
        return false;
      }
      uni.navigateTo({
        url: "/message/messageApproval",
      });
    },

    goContract() {
      if (this.checkIdentity()) {
        return false;
      }
      uni.navigateTo({
        url: "/contract/index",
      });
    },
    goNotice() {
      if (this.checkIdentity()) {
        return false;
      }
      uni.navigateTo({
        url: "/announcement/index",
      });
    },
    // 去补充资料
    goInfoProgress() {},
    goXiaoxiTongzhi() {
      if (this.checkIdentity()) {
        return false;
      }
      uni.navigateTo({
        url: "/notification/index",
      });
    },

    // 请求公司公告列表
    getSysNoticeList(companyId) {
      listSysNoticeByUser(companyId).then((res) => {
        this.noticelist = res;
      });
    },
    // 请求个人信息
    getMyInfo() {
      getMyInfoReq().then((res) => {
        this.myInfo = {
          companyName: res.companyName,
          percentage: res.percentage,
          name: res.name,
          avatar: res.avatar
        };
        this.userStatus = res.status;
        //该接口是否在职状态1 是在职2是离职 登录接口返回 离职是4在职是2
        uni.setStorageSync("userStatus", res.status);
        this.$store.commit("user/updateUserInfo")
      });
    },
    getSwitch() {
      getSwitch().then((res) => {
        if (res !== null && res !== undefined) {
          this.isSwitch = res;
        }
      });
    },
    goVerify() {
      uni.navigateTo({
        url: "/authorize/select",
      });
    },
    checkIdentity() {
      const token = uni.getStorageSync("token");
      if (token) {
        return false;
      } else {
        uni.redirectTo({
          url: "/authorize/index",
        });
      }
    },
  },
};
</script>
<style lang="scss">
.moduleBox {
  position: relative;
  border-radius: 20rpx;
  height: 140rpx;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.yilizhi {
  height: 14px;
  background: #b5b5b5;
  border-radius: 2px;
  width: 36px;
  text-align: center;
  line-height: 15px;
  color: #fff;
  margin: 0 6px;
  font-size: 10px;
}
.top-top {
  padding-top: 18px;
  padding-bottom: 18px;
  padding-left: 16px;
  padding-right: 16px;
  height: auto;
  background: #ffffff;
  border-radius: 8px;
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  justify-content: space-between;
  .top-t {
    width: 70%;
  }
}
.top-top-hangye {
  padding: 15px;
  background: #ffffff;
  border-radius: 10px;
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  justify-content: space-between;
}
.hangye-m {
  height: 100%;
  width: 100%;
  flex-direction: column;
  display: flex;
  margin-right: 13px;
  justify-content: space-between;
}
.hangye-title {
  margin-bottom: 7px;
  font-size: 16px;
  color: #222426;
}
.top-m {
  display: flex;
  margin-bottom: 5px;
  align-items: center;
}
.top-m2 {
  display: flex;
  margin-bottom: 3px;
  align-items: center;
}

.top-renz {
  font-size: 12px;
  color: #ffa600;
}
.top-xinxi {
  font-size: 12px;
  color: $uni-color-primary;
}
.top-hangye {
  font-size: 12px;
  color: #9c9c9c;
}
.top-renzhen {
  height: 16px;
  width: 16px;
}
.top-renzhen2 {
  height: 16px;
  width: 16px;
  margin-left: 5px;
  margin-right: 5px;
}
.userinfo-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
}
.hangye-img {
  display: flex;
  align-items: center;
  width: 123px;
  height: 100%;
  .hangye-img2 {
    border-radius: 10%;

    width: 123px;
    height: 68px;
  }
}
.background-top {
  padding-top: 12px;
  width: 100%;
  border-bottom-right-radius: 70px;
  border-bottom-left-radius: 70px;
  background-color: $uni-color-primary;
}
.flow-image2 {
  position: absolute;
  z-index: -1;
  height: 72px;
  width: 92%;
}
.work-top2 {
  height: 50px;
  font-size: 18px;
  font-weight: 500;
  color: rgba(34, 36, 38, 1);
  line-height: 50px;
  margin-left: 18px;
}
.jiantou {
  width: 24px;
  height: 24px;
}
.images22 {
  width: 42px;
  height: 50px;
  position: absolute;
  bottom: -17px;
}
.intoJob {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 15px;
  background: #ffffff;
  border-radius: 10px;
  margin: 16px 15px;
}
.intoJob1 {
  display: flex;
  position: relative;
  justify-content: flex-start;
  align-items: center;
  font-size: 14px;
  font-weight: 500;
  color: #222426;
}
.intoJob1Boxyzm {
  font-size: 12px;
  font-weight: 400;
  color: #9c9c9c;
}
.intoJob1Box {
  padding-right: 15px;
}
.showModalTitle {
  font-size: 12px;
  margin-top: 5px;
  color: #aaaaaa;
  text-align: center;
}
.marBottom24 {
  margin-bottom: 24px;
}
.qrrz {
  font-size: 14px;
  color: #ffffff;
  line-height: 20px;
  margin-bottom: 32px;
  background: $uni-color-primary;
  border-radius: 22px;
  padding: 12px 56px;
  display: inline-block;
}
.colB9B {
  color: #b9b9b9;
}
</style>
